#include"serial.h"
#include"bsp_led.h"
uint8_t xdata RX1_Buffer[DATA_length];
uint8_t RX1_write=0,RX1_read=0;

uint8_t xdata TX1_Buffer[DATA_length];
uint8_t TX1_write=0,TX1_read=0;
bit uart_flag=0;
bit B_TX1_Busy=0;
void Uart1_Init(void)		//
{
	SCON = 0x50;		//8位数据,可变波特率
	AUXR |= 0x01;		//串口1选择定时器2为波特率发生器
	AUXR |= 0x04;		//定时器2时钟为Fosc,即1T
	T2H = (Timer2_Reload >> 8);
	T2L = Timer2_Reload;
	AUXR |= 0x10;		//启动定时器2
//	REN = 1;	//允许接收
//	ES  = 1;	//允许中断								    
}
//void UART1 (void) interrupt 4
//{
//	if(RI)
//	{
//		    RI = 0;
//			RX1_Buffer[RX1_write] = SBUF;		//保存一个字节
//
//			if(++RX1_write >= DATA_length)	RX1_write = 0;	//避免溢出处理
//	}
//	if(TI)
//	{
//		TI = 0;
//		B_TX1_Busy=0;
//		if(TX1_write==TX1_read)REN = 1;
//	}
//}
void UART1 (void) interrupt 4
{
	if(RI)
	{
		    RI = 0;
			RX1_Buffer[RX1_write] = SBUF;		//保存一个字节
			if(RX1_write>=3)   //每次从手机发送给ESP8266的头会有\r\n要避免检测头，给主程序发送接受完毕的假象，防止丢失数据。
			{
				if((RX1_Buffer[RX1_write]=='\n')&&(RX1_Buffer[RX1_write-1]=='\r'))
				{uart_flag=1;}
			}
			if(++RX1_write >= DATA_length-1)	RX1_write = 0;	//避免溢出处理
	}
	if(TI)
	{
		TI = 0;
		B_TX1_Busy=0;
		if(TX1_write==TX1_read)REN = 1;
	}
}
void uart_send()
{
	if(B_TX1_Busy==0)
		{
			
			if(TX1_write!=TX1_read)
		    {				
							REN = 0;
							B_TX1_Busy=1;
							SBUF = TX1_Buffer[TX1_read];	//发一个字节
							if(++TX1_read >= DATA_length)	TX1_read = 0;	//避免溢出处理
						
						
			}	
		}
}
void esp8266_send(uint8_t *pStr)
{
			while(*pStr != '\0')
			{			
					SBUF = *pStr;	//发一个字节
					while(!TI);
					TI=0;
					pStr++;
					
			}
					
}
void Put_uart(uint8_t *pStr)
{
	while(*pStr != '\0')
	{
		TX1_Buffer[TX1_write]=*pStr;
		pStr++;
		if(++TX1_write >= DATA_length)	TX1_write = 0;	//避免溢出处理	
	}

}